package com.sky.wsp.sql.scanner.patterns;

import cn.hutool.core.util.StrUtil;
import com.sky.wsp.sql.scanner.utils.MyFileUtil;
import com.sky.wsp.sql.scanner.vo.MatchResult;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author wangshaopeng@talkweb.com.cn
 * @desccription 通用关键字匹配管理器，不区分开发语言，全部进行关键字匹配
 * @date 2024/11/16
 */
public class CommonPatternManager {

    /**
     * 对内容进行关键字匹配
     *
     * @param content
     * @param patterns 正则表达式所在的配置文件
     * @return
     */
    public static List<MatchResult> match(String content, Map<String, Pattern> patterns) {
        if(StrUtil.isEmpty(content) || patterns == null || patterns.isEmpty()) {
            return Collections.emptyList();
        }
        List<MatchResult> list = new ArrayList<>();
        Set<Map.Entry<String, Pattern>> entries = patterns.entrySet();
        for (Map.Entry<String, Pattern> entry : entries) {
            String patternName = entry.getKey();
            Pattern pattern = entry.getValue();
            int i = 0;
            Matcher matcher = pattern.matcher(content);
            while (matcher.find()) {
                ++i;
            }
            if (0 == i) {
                continue;
            }
            MatchResult r = new MatchResult();
            r.setKey(patternName);
            r.setCount(i);
            list.add(r);
        }
        ;
        return list;
    }

    public static Map<String, Pattern> getPatterns(String patternFileSimpleName) {
        if(null == patternFileSimpleName) {
            return null;
        }
        Set<String> linesAsSet = MyFileUtil.getLinesAsSet(patternFileSimpleName);
        Map<String, Pattern> patterns = new HashMap<>();
        for (String line : linesAsSet) {
            patterns.put(line, Pattern.compile(line));
        }
        return patterns;
    }
}
